#!/usr/bin/env bash

#
if [ `whoami` != "root" ];then
  echo "must be root"
  exit 1
fi

echo "手动安装Docker ..."
# https://docs.docker.com/engine/install/debian/#install-from-a-package

mkdir -p /opt/docker

mkdir -p /etc/docker

#### 设置存储位置，需要提前执行以下命令 ####
# mkdir -p /data/docker
# ln -s /data/docker /var/lib/docker

if [ ! -f /etc/docker/daemon.json ]; then
cat <<EOF > /etc/docker/daemon.json
{
"registry-mirrors":[
    "https://hub-mirror.c.163.com",
    "https://registry.aliyuncs.com"
],
"graph":"/var/lib/docker",
"insecure-registries":["localhost:8000"],
"features": { "buildkit": true }
}
EOF
fi

os=$(lsb_release -is | tr 'A-Z' 'a-z')
os_code=$(lsb_release -cs)
cpu=$(dpkg --print-architecture)

if [ "$os" == "deepin" ]; then
  echo "检测到是 DeepinOs，进行 Debian 系统替换！"
  os='debian'

  if [ "${os_code}" == "apricot" ]; then
    os_code="buster"
  else
    echo "不识别的 debian 系统代码 ${os_code} !"
  fi
fi


echo $os:$os_code:$cpu

base_url="https://download.docker.com/linux/${os}/dists/${os_code}/pool/stable/${cpu}"

cd /opt/docker && echo "切换到 `pwd`"

curl "$base_url/" > /opt/docker/docker-deb.list

function important(){
  c="$1"

  echo -e "\033[41;37m=================\033[0m"
  echo -e "\033[41;37m${c}\033[0m"
  echo -e "\033[41;37m=================\033[0m"
}

function install(){
  c="$1"

  v1=$(cat /opt/docker/docker-deb.list | grep -E "${c}_.*.deb" | cut -d '"' -f 2 | cut -d '_' -f 2 | sort -rV | head -1)
  c1=$(cat /opt/docker/docker-deb.list | grep -E "${c}_.*.deb" | cut -d '"' -f 2 | grep -E "${c}_${v1}.*.deb")

  echo "curl -OJ -s $base_url/$c1"
  curl -OJ -s "$base_url/$c1"

  if [ ! -f "./${c1}" ]; then
       important "找不到文件：`pwd`/${c1}"
       exit 1
  fi

  echo "dpkg -i "./${c1}""
  sudo dpkg -i "./${c1}"

  if [ $? != 0 ]; then
    important "执行 dpkg -i ./${c1} 错误！"
    exit 1
  fi
}


echo "如果安装时依赖错误，运行： sudo apt --fix-broken install"
install "containerd.io"
install "docker-ce"
install "docker-ce-cli"
install "docker-compose-plugin"


echo "开机启动docker..."
systemctl start docker
systemctl enable docker






